Components.utils.import("resource://gre/modules/Services.jsm");

var OpenID4Fennec = {
  _OpenIdStorage : null,
  
  getOpenIdStorage : function _getOpenIdStorage (){
    if (!OpenID4Fennec._OpenIdStorage) {
    	OpenID4Fennec._OpenIdStorage = Components.classes['@openinfocard.com/openidstorage;1']
        .getService().wrappedJSObject;
    }
    return OpenID4Fennec._OpenIdStorage;
  },

  log : function (msg) {
//      Services.console.logStringMessage("OpenID4Fennec: " + msg);
  },

  prefs : null,
  
  uiReadyDelayed : function() {
    try {
      //PageActions.register("openidnascar-action", OpenID4Fennec.pageaction);
    } catch (e) {
      Components.utils.reportError(e);
    }
  },
  
  load : function () {
    try {
//      OpenID4Fennec.log("load start");
      removeEventListener("load", OpenID4Fennec.load, false);
    } catch (e) {
      Components.utils.reportError(e);
    }
	try {      
      // Listener to initialize options panel state when it's available.
      document.getElementById("addons-list").addEventListener("AddonOptionsLoad", OpenID4Fennec.optionsLoad, false);
    } catch (e) {
      Components.utils.reportError(e);
    }
	try {      
      // tapLong on a password field initiates tap-password entry.
      // We send all long taps to the content script to find out if they were 
      // tapped on an input[type=password] field; this listener receives
      // the message back from content.
      messageManager.addMessageListener("OpenID4Fennec:tapLong", OpenID4Fennec.tapLongEvent);
      
      messageManager.loadFrameScript("chrome://openidnascar/content/content_script.js", true);
    } catch (e) {
      Components.utils.reportError(e);
    }
	try {      
      // TapLong listener to send TapLong events to the content script.
      document.addEventListener("TapLong", OpenID4Fennec.chromeTapLong, false);
    } catch (e) {
      Components.utils.reportError(e);
    }
	try {      
      OpenID4Fennec.prefs = Components.classes["@mozilla.org/preferences-service;1"].getService(Components.interfaces.nsIPrefService).getBranch("extensions.OpenID4Fennec.");
      OpenID4Fennec.prefs.QueryInterface(Components.interfaces.nsIPrefBranch2);
      OpenID4Fennec.prefs.addObserver("", OpenID4Fennec, false);
    } catch (e) {
      Components.utils.reportError(e);
    }
	try {      
      addEventListener("unload", OpenID4Fennec.unload, false);
    } catch (e) {
      Components.utils.reportError(e);
    }
	try {
	  window.addEventListener("UIReadyDelayed", OpenID4Fennec.uiReadyDelayed, true);   
    } catch (e) {
      Components.utils.reportError(e);
    }
  },
    
    unload : function () {
      try {
//        OpenID4Fennec.log("load start");
        removeEventListener("unload", OpenID4Fennec.unload, false);
        
        document.getElementById("addons-list").removeEventListener("AddonOptionsLoad", OpenID4Fennec.optionsLoad, false);
        
        document.removeEventListener("TapLong", OpenID4Fennec.chromeTapLong, false);
        
        messageManager.removeMessageListener("OpenID4Fennec:tapLong", OpenID4Fennec.tapLongEvent);
        
        OpenID4Fennec.prefs.removeObserver("", OpenID4Fennec);
      } catch (e) {
        Components.utils.reportError(e);
      }
    },
    
    observe : function(subject, topic, data) {
      if (topic != "nsPref:changed") {
        return;
      }
      
//      switch(data) {
//        case "neverPrompt":
//          TAPSURE.toggleResetButton();
//        break;
//      }
    },
    
    chromeTapLong : function (aEvent) {
      try {
        OpenID4Fennec.log("chromeTapLong x="+aEvent.clientX + " y=" + aEvent.clientY);
//        if (OpenID4Fennec.patterns.length > 0) {
          var browser = getBrowser();
        
          var pos = browser.transformClientToBrowser(aEvent.clientX, aEvent.clientY);
        
          browser.messageManager.sendAsyncMessage("OpenID4Fennec:chromeTapLong", pos);
//        }
      } catch(e) {
        Components.utils.reportError(e);
      }
    },
    
    onchange : function (event) {
      try {
//        OpenID4Fennec.log("onchange");
        let doc = event.target.ownerDocument;
        let elt = doc.getElementById("openidprovidertextbox");
        let value = elt.value;
//        OpenID4Fennec.log("onchange value=" + value);
        if (value && (value.trim() != "")) {
          try {
            OpenID4Fennec.getOpenIdStorage().setPreferredOpenID(value);
          } catch (ex) {
            OpenID4Fennec.log("onchange Exception: " + ex);
          }
        }
      } catch(e) {
        Components.utils.reportError(e);
      }
    },
    
    optionsLoad : function (event) {
      try {
//      OpenID4Fennec.log("optionsLoad");
      let addon = event.target;
      if (addon) {
//        OpenID4Fennec.log("optionsLoad addon");
        let box = document.getAnonymousElementByAttribute(addon, "anonid", "options-box");
        if (box) {
//          OpenID4Fennec.log("optionsLoad box");
          var bundleService = Components.classes["@mozilla.org/intl/stringbundle;1"]
            .getService(Components.interfaces.nsIStringBundleService);
          var browserBundle = bundleService
            .createBundle("chrome://openidnascar/locale/openid.properties");

          let doc = box.ownerDocument;
          let myBox = doc.createElement("vbox");
          myBox.setAttribute("flex", "1");
          myBox.setAttribute("class", "openidnascarbox");
          let caption = doc.createElement("label");
          let label = browserBundle.GetStringFromName("openidnascar.prefs.provider");
          caption.setAttribute("value", label);
          caption.setAttribute("control", "openidprovidertextbox");
          myBox.appendChild(caption);
          let settingInputBox = doc.createElement("box");
          let textbox = doc.createElement("textbox");
          textbox.setAttribute("id", "openidprovidertextbox");
          textbox.setAttribute("type", "autocomplete");
          textbox.setAttribute("autocompletesearch", "openid_url");
          let value = OpenID4Fennec.getOpenIdStorage().getPreferredOpenID();
          if (!value) {
        	  value = "";
          }
          textbox.setAttribute("value", value);
          textbox.setAttribute("placeholder", label);
          textbox.addEventListener("change", OpenID4Fennec.onchange, false);
          settingInputBox.appendChild(textbox);
          myBox.appendChild(settingInputBox);
          box.appendChild(myBox);
        } else {
//          OpenID4Fennec.log("optionsLoad !box");
        }
      } else {
//        OpenID4Fennec.log("optionsLoad !addon");
      }
      } catch (e) {
        Components.utils.reportError(e);
      }
  },

  insertOpenID : function () {
	try {
//	  OpenID4Fennec.log("insertOpenID");
      var preferredOpenidProvider;
      try {
        var OpenIdStorage = Components.classes['@openinfocard.com/openidstorage;1']
          .getService().wrappedJSObject;
        preferredOpenidProvider = OpenIdStorage.getPreferredOpenID();
//        OpenID4Fennec.log("insertOpenID preferredOpenidProvider=" +
//            preferredOpenidProvider);
      } catch(e) {
        Components.utils.reportError(e);
        return;
      }
      if (!preferredOpenidProvider) {
//        OpenID4Fennec.log("insertOpenID !preferredOpenidProvider");
        //OpenID4Fennec.noOpenIdYet(aEvent);
        return;
      }
      var browser = getBrowser();
      var obj = {};
      obj.preferredOpenidProvider = preferredOpenidProvider;
      browser.messageManager.sendAsyncMessage("OpenID4Fennec:chromeToolbarClick", obj);
    } catch (e) {
      Components.utils.reportError(e);
    }
  },
	    
  chromeToolbarClick : function () {
    try {
//      OpenID4Fennec.log("chromeToolbarClick");
      OpenID4Fennec.insertOpenID();
    } catch (e) {
      Components.utils.reportError(e);
    }
  },

    openOptionMenu : function(element) {
      try {
//        OpenID4Fennec.log("openOptionMenu");
        BrowserUI.showPanel("addons-container");
        ExtensionsView.showOptions("openid_nascar@openinfocard.org");
        let openidprovidertextbox = document.getElementById("openidprovidertextbox");
        if (openidprovidertextbox) {
        	openidprovidertextbox.focus();
        }
      } catch (e) {
        Components.utils.reportError(e);
      }
    },
    
    pageactionClick : function() {
      try {
//        OpenID4Fennec.log("pageactionClick");
        OpenID4Fennec.insertOpenID();
      } catch (e) {
        Components.utils.reportError(e);
      }
    },
    
    pageaction : function(element) {
      try {
//        OpenID4Fennec.log("pageaction");
        
        if (getBrowser().currentURI == "about:blank")
          return false;

          var preferredOpenidProvider;
          try {
            var OpenIdStorage = Components.classes['@openinfocard.com/openidstorage;1']
              .getService().wrappedJSObject;
            preferredOpenidProvider = OpenIdStorage.getPreferredOpenID();
//            OpenID4Fennec.log("chromeToolbarClick preferredOpenidProvider=" +
//                preferredOpenidProvider);
          } catch(e) {
            Components.utils.reportError(e);
            return;
          }
              var bundleService = Components.classes["@mozilla.org/intl/stringbundle;1"]
        .getService(Components.interfaces.nsIStringBundleService);
              var browserBundle = bundleService
        .createBundle("chrome://openidnascar/locale/openid.properties");

          if (!preferredOpenidProvider) {
            var message = browserBundle.GetStringFromName("openidnascar.pageaction.setopenidinoptionsmenu");
            element.setAttribute("description", message);
            element.addEventListener("click", OpenID4Fennec.openOptionMenu);
          } else {
            var message = browserBundle.GetStringFromName("openidnascar.pageaction.description"); 
            element.setAttribute("title", message);
            element.setAttribute("description", preferredOpenidProvider);
            element.addEventListener("click", OpenID4Fennec.chromeToolbarClick);
          }
          
        return true;
      } catch (e) {
        Components.utils.reportError(e);
      return false;
      }
    },
    
    tapLongEvent : function (msg) {
      try {
//        OpenID4Fennec.log("tapLongEvent msg.json.fieldId=" + msg.json.fieldId);
//        OpenID4Fennec.returnMessageManager = msg.target.QueryInterface(Components.interfaces.nsIFrameLoaderOwner).frameLoader.messageManager;
//        OpenID4Fennec.relevantPasswordFieldId = msg.json.fieldId;
//        OpenID4Fennec.showPatternAttemptDialog();
      } catch(e) {
        Components.utils.reportError(e);
      }
    }
    
};

addEventListener("load", OpenID4Fennec.load, false);